package com.jy.controller.filemanager;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jy.common.ajax.AjaxRes;
import com.jy.common.mybatis.Page;
import com.jy.common.utils.base.Const;
import com.jy.common.utils.base.Tools;
import com.jy.controller.base.BaseController;
import com.jy.entity.filemanager.SourceInfo;
import com.jy.entity.filemanager.TSTaske;
import com.jy.service.filemanager.taskmain.TaskMainService;

@Controller
@RequestMapping("/maintask")
public class TaskMainController extends BaseController<TSTaske> {

	@Autowired
	private TaskMainService service;
	@Autowired
	private Scheduler scheduler;

	/**
	 * @api {post} /maintask/findBypage  任务分页列表查询
	 * 
	 * @apiName findBypage
	 * @apiGroup maintask
	 * @apiParam {Object} Page<TSProduct> 分页对象
	 * @apiSuccess {Object} obj 1.resMsg 2.obj
	 * @apiParam {Object} TSProduct 任务对象
	 */
	@RequestMapping(value = "findBypage", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes index(Page<TSTaske> page, TSTaske o) {
		AjaxRes ar = getAjaxRes();
		try {
			Page<TSTaske> result = service.findByPage(o, page);
			Map<String, Object> p = new HashMap<String, Object>();
			p.put("list", result);
			ar.setSucceed(p);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	@RequestMapping(value = "findRealHiTask", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes findRealHiTask() {
		AjaxRes ar = getAjaxRes();
		try {
			Map<String, Object> p = new HashMap<String, Object>();
			p.put("allSUm", service.findRealHiTask("task"));
			p.put("fileSum", service.findRealHiTask("file"));
			p.put("errorSum", service.findRealHiTask("problem"));
			ar.setSucceed(p);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	/**
	 * @api {post} /maintask/find  任务列表查询
	 * 
	 * @apiName find
	 * @apiGroup maintask
	 * @apiParam {Object} Page<TSProduct> 分页对象
	 * @apiSuccess {Object} obj 1.resMsg 2.obj
	 * @apiParam {Object} TSProduct 任务对象
	 */
	@RequestMapping(value = "find", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes find(TSTaske o) {
		AjaxRes ar = getAjaxRes();
		try {
			TSTaske obj = service.findTaskById(o);
			// obj.setCronExpression(getCronExpression(obj));
			// ScheduleTaskUtils.createScheduleJob(scheduler, obj);
			ar.setSucceed(obj);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	/**
	 * @api {post} /maintask/add  任务添加
	 * 
	 * @apiName add
	 * @apiGroup maintask
	 * @apiParam {Object} Page<TSProduct> 分页对象
	 * @apiSuccess {Object} obj 1.resMsg 2.obj
	 * @apiParam {Object} TSProduct 任务对象
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(TSTaske o) {
		AjaxRes ar = getAjaxRes();
		try {
			int res = 0;
			o.setStatus(1);// 启动
			o.setFileNum(0);
			if (2 == o.getExecutionMode()) {
				o.setCronExpression(getMoreCorn(o));// 计算任务执行时间表达式
			} else {
				o.setCronExpression(getCronExpression(o, "", ""));// 计算任务执行时间表达式
			}
			JSONArray jsonArr = JSONArray.fromObject(o.getSourceId());// 转换成JSONArray
			List<SourceInfo> sourceList = JSONArray.toList(jsonArr,
					SourceInfo.class);// 获得产品数组
			// 源多个
			for (SourceInfo obj : sourceList) {
				o.setSourceId(obj.getId());
				o.setIsSubFile(obj.getIsSubFile());
				if (sourceList.size() > 1) {
					o.setId(get32UUID());
					o.setTaskCode(generateShortUuid());
					res = service.creatTask(o);
				} else {
					// 目的多个
					String[] arr = o.getAimsIds().split(",");
					for (String strAim : arr) {
						o.setTaskCode(generateShortUuid());
						System.out.println(">?" + strAim.length());
						o.setAimsIds(strAim);
						o.setId(get32UUID());
						res = service.creatTask(o);
					}
				}
			}

			if (res == 1)
				ar.setSucceedMsg(Const.SAVE_SUCCEED);
			else
				ar.setFailMsg(Const.SAVE_FAIL);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		return ar;
	}

	public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
			"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
			"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
			"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
			"W", "X", "Y", "Z" };

	public static String generateShortUuid() {
		StringBuffer shortBuffer = new StringBuffer();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < 8; i++) {
			String str = uuid.substring(i * 4, i * 4 + 4);
			int x = Integer.parseInt(str, 16);
			shortBuffer.append(chars[x % 0x3E]);
		}
		return shortBuffer.toString();

	}

	/**
	 * @api {post} /maintask/update  任务更新
	 * 
	 * @apiName update
	 * @apiGroup maintask
	 * @apiParam {Object} Page<TSProduct> 分页对象
	 * @apiSuccess {Object} obj 1.resMsg 2.obj
	 * @apiParam {Object} TSProduct 任务对象
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes update(TSTaske o) {
		AjaxRes ar = getAjaxRes();
		try {
			// 如果选择覆盖初始时间则将最近更新时间修改为修改后时间
			// 0覆盖
			TSTaske newObjTaske = service.findTaskById(o);

			if (o.getIsChangeDate() != null && 0 == o.getIsChangeDate()) {
				o.setNewDate(o.getStartDate());
			} else {
				o.setNewDate(newObjTaske.getNewDate());
			}
			if (2 == o.getExecutionMode()) {
				o.setCronExpression(getMoreCorn(o));// 计算任务执行时间表达式
			} else {
				o.setCronExpression(getCronExpression(o, "", ""));// 计算任务执行时间表达式
			}
			int res = service.updateTask(o);
			if (res == 1)
				ar.setSucceedMsg(Const.UPDATE_SUCCEED);
			else
				ar.setFailMsg(Const.UPDATE_FAIL);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.UPDATE_FAIL);
		}
		return ar;
	}

	/**
	 * @api {post} /maintask/del  任务删除
	 * 
	 * @apiName del
	 * @apiGroup maintask
	 * @apiParam {Object} Page<TSProduct> 分页对象
	 * @apiSuccess {Object} obj 1.resMsg 2.obj
	 * @apiParam {Object} TSProduct 任务对象
	 */
	@RequestMapping(value = "del", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes del(TSTaske o) {
		AjaxRes ar = getAjaxRes();
		try {
			int res = service.deleteTask(o);
			if (res == 1)
				ar.setSucceedMsg(Const.DEL_SUCCEED);
			else
				ar.setFailMsg(Const.DEL_FAIL);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DEL_FAIL);
		}
		return ar;
	}

	/**
	 * @api {post} /maintask/stopTaskJob  任务暂停
	 * 
	 * @apiName stopTaskJob
	 * @apiGroup maintask
	 * @apiParam {Object} Page<TSProduct> 分页对象
	 * @apiSuccess {Object} obj 1.resMsg 2.obj
	 * @apiParam {Object} TSTaske 任务对象
	 */
	@RequestMapping(value = "stopTaskJob", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes stopTaskJob(TSTaske o) {
		AjaxRes ar = getAjaxRes();
		try {
			service.stopTaskJob(o);
			ar.setSucceedMsg(Const.DEL_SUCCEED);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DEL_FAIL);
		}
		return ar;
	}

	/**
	 * @api {post} /maintask/resetTaskJob  任务重启
	 * 
	 * @apiName resetTaskJob
	 * @apiGroup maintask
	 * @apiParam {Object} Page<TSProduct> 分页对象
	 * @apiSuccess {Object} obj 1.resMsg 2.obj
	 * @apiParam {Object} TSTaske 任务对象
	 */
	@RequestMapping(value = "resetTaskJob", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes resetTaskJob(TSTaske o) {
		AjaxRes ar = getAjaxRes();
		try {
			service.resetTaskJob(o);
			ar.setSucceedMsg(Const.DEL_SUCCEED);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DEL_FAIL);
		}
		return ar;
	}

	private String getMoreCorn(TSTaske o) {
		String corn = "";
		String[] obj = o.getTimeList().split(";");
		for (String str : obj) {
			if (Tools.notEmpty(str)) {
				String[] newStr = str.split(":");
				if (newStr.length > 1) {
					corn += ";" + getCronExpression(o, newStr[0], newStr[1]);
				}
			}
		}
		return corn.length() > 0 ? corn.substring(1) : corn;
	}

	// 根据任务时间获取定时任务表达式
	private String getCronExpression(TSTaske o, String hourStr, String minStr) {
		String cronExp = "";
		Date starDate = o.getExStartDate();
		Date endDate = o.getExEndDate();
		Integer type = o.getTimeType();// 执行时间类别 1.分钟 2.小时
		String weekStr = o.getWeek();
		Integer mode = o.getExecutionMode();// 0一次 1 多次
		Integer timeNum = o.getTimeNum();
		// 每天
		if (o.getExecutionType().equals(1)) {
			if (0 == mode) {
				cronExp += "0" + " ";
				cronExp += starDate.getMinutes() + " ";
				cronExp += starDate.getHours();
				cronExp += " * * ?";
			} else if (1 == mode) {
				if (type.equals(1)) {
					cronExp += "0 0/" + timeNum + " ";
					cronExp += starDate.getHours() + "-";
					cronExp += endDate.getHours() + " * * ?";

				} else {
					cronExp += "0 0/100 ";
					cronExp += starDate.getHours() + "/";
					cronExp += timeNum + " * * ?";

				}
			} else if (2 == mode) {
				cronExp += "0" + " ";
				cronExp += minStr + " ";
				cronExp += hourStr + " ";
				cronExp += " * * ?";
			}

		}
		// 每周
		else if (o.getExecutionType().equals(2)) {
			if (0 == mode) {
				cronExp += "0" + " ";
				cronExp += starDate.getMinutes() + " ";
				cronExp += starDate.getHours() + " ";
			} else if (1 == mode) {
				if (type.equals(1)) {
					cronExp += "0 0/" + timeNum + " ";
					cronExp += starDate.getHours() + "-";
					cronExp += endDate.getHours() + " ";
				} else {
					cronExp += "0 0/100 ";
					cronExp += starDate.getHours() + "/";
					cronExp += timeNum + " ";
				}
			} else if (2 == mode) {
				cronExp += "0" + " ";
				cronExp += minStr + " ";
				cronExp += hourStr + " ";
			}
			cronExp += "? * " + weekStr;
		}
		// 每月
		else if (o.getExecutionType().equals(4)) {
			if (0 == o.getMonthType()) {
				cronExp = "0 0 0 L * ?";
			} else {
				cronExp = "0 0 0 " + o.getMonthDay() + " * ?";
			}
		}

		else {
			// 实时 默认为1分钟
			cronExp = "0 0/1 * * * ?";
		}
		return cronExp;

	}
}
